package es.cazadoresmadridejos.beans.dao.budget.impl;

import java.sql.SQLException;
import java.util.List;

import org.displaytag.pagination.PaginatedList;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import es.cazadoresmadridejos.beans.dao.budget.BudgetDao;
import es.cazadoresmadridejos.common.bean.dao.impl.DaoImpl;
import es.cazadoresmadridejos.model.Budget;
import es.cazadoresmadridejos.model.BudgetLine;
import es.cazadoresmadridejos.objs.web.Page;
import es.cazadoresmadridejos.objs.web.PaginatedListImpl;

@SuppressWarnings("unchecked")
@Repository("budgetDao")
public class BudgetDaoImpl extends DaoImpl<Budget> implements BudgetDao{

	@Override
	public Budget newInstance() {
		return new Budget();
	}

	@Override
	public PaginatedList findAllPaginated(final Page page) {
		return (PaginatedList) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql
				.append("select b ")
				.append(" from Budget b ")
				.append(getSort(page, "b"));

				StringBuilder hqlCount = new StringBuilder("select count(b) from Budget b");
				Query query = session.createQuery(hql.toString());
				Query queryCount = session.createQuery(hqlCount.toString());

				query.setMaxResults(page.getLimit());
				query.setFirstResult(page.getLimit() * (page.getPage() - 1));

				return new PaginatedListImpl<Object>(query.list(), 
						page, 
						((Long)queryCount.uniqueResult()).intValue());
			}
		});
	}

	@Override
	public List<BudgetLine> getLines(final Long budget) {
		return (List<BudgetLine>) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql.append("select bl ")
				.append(" from BudgetLine bl ")
				.append(" where bl.budget.id = :bid")
				.append("");
				
				Query query = session.createQuery(hql.toString());
				query.setLong("bid", budget);
				
				return query.list();
			}
		});
	}

	@Override
	public Budget getByReason(final Long id) {
		return (Budget) getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {

				StringBuilder hql = new StringBuilder();
				hql
					.append("select b ")
					.append(" from Budget b ")	
					.append(" where b.reason.id  = :reasonid ")
					.append("");
				
				Query query = session.createQuery(hql.toString());

				query.setLong("reasonid", id);
				
				return query.uniqueResult();
			}
		});
	}

}
